﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web.UI;
using UMC.Web;
using UMC.Net;
using System.IO;

namespace UMC.Wiki.Activities
{

    class SubjectEditUIActivity : WebActivity
    {

        private static string CreateToken(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = System.Text.UTF8Encoding.UTF8; ;
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashmessage);
            }
        }
        void Send(WebRequest request, Subject sub, string cid, bool robot)
        {
            if (sub.project_id.HasValue == false)
            {
                return;
            }

        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var Id = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Id", g =>
           {
               this.Prompt("请输入参数");
               return this.DialogValue("none");
           }));


            var sub = DataFactory.Instance().Subject(Id.Value);//  subEntity.Single();

            var user = this.Context.Token.Identity();

            if (sub.project_id.HasValue)
            {
                var member = DataFactory.Instance().ProjectMember(sub.project_id.Value, user.Id.Value);

                if (member != null)
                {
                    switch (member.AuthType)
                    {
                        case WebAuthType.Admin:
                        case WebAuthType.User:
                            break;
                        default:
                            if (sub.Status > 0)
                            {
                                this.Context.Send(new UISectionBuilder(request.Model, "UIData", new UMC.Web.WebMeta().Put("Id", Id))

                                        .Builder(), true);

                            }
                            this.Prompt("您未有编辑此图文的权限");
                            break;
                    }

                }
                else
                {
                    if (sub.Status > 0)
                    {
                        this.Context.Send(new UISectionBuilder(request.Model, "UIData", new UMC.Web.WebMeta().Put("Id", Id))

                                .Builder(), true);
                    }
                    this.Prompt("您未有编辑此图文的权限");
                }
            }

            var imageKey = sub.Id.Value.ToString();
            var Model = this.AsyncDialog("Model", gKey =>
            {

                var webr = UMC.Web.WebResource.Instance();


                UITitle uITItle = UITitle.Create();
                uITItle.Title = "发布设置";
                var sestion = UISection.Create(uITItle);

                var items = new List<WebMeta>();

                var indes = Utility.BitIndex(sub.ImageIndexs ?? 0);
                UMC.Data.Utility.Each(indes, dr =>
                    {
                        items.Add(new UMC.Web.WebMeta().Put("src", webr.ImageResolve(request.Url, imageKey, dr, "3", $"_{sub.ImageIndexs}")).Put("click", new Web.UIClick(new UMC.Web.WebMeta().Put("Id", sub.Id.Value).Put("Seq", dr).Put(gKey, "Picture"))
                        {
                            Model = request.Model,
                            Command = request.Command
                        }));
                    });
                var uidesc = new UIDesc(sub.Title);
                uidesc.Style.Bold().Height(50);
                uidesc.Click(new UIClick(request, "Id", Id.ToString(), gKey, "Title"));

                var nine = new UMC.Web.WebMeta().Put("images", items);

                sestion.Delete(uidesc, new UIEventText().Click(new UIClick(request, "Id", Id.ToString(), gKey, "Del")));
                var sT = sub.Description ?? sub.Title;
                if (sT.Length > 48)
                {
                    sT = sT.Substring(0, 48) + "...";
                }
                var desc = new UIDesc(sT);
                desc.Style.Height(40).Color(0x999).Size(13);
                desc.Click(new UIClick(request, "Id", Id.ToString(), gKey, "Desc"));
                sestion
                .Add(UICell.Create("NineImage", nine)).Add(desc)
                .AddCell("封面方式", sub.IsPicture == true ? "显示大图" : (indes.Length > 2 ? "三张图" : "单张图")
                , new UIClick(request, "Id", Id.ToString(), gKey, "Show"));
                if (indes.Length < 3)
                {
                    nine.Put("click", new UIClick(request, "Id", Id.ToString(), gKey, "Image"));

                }
                if (request.IsApp)
                {
                    sestion.NewSection().AddCell('\uf044', "编辑正文", "", new UIClick(Id.ToString()) { Command = "Content", Model = request.Model });

                }
                var status = "审阅中";

                if (sub.Status > 0)
                {
                    status = "已发布";
                }
                else if (sub.Status < 0)
                {
                    if (sub.Status == -2)
                    {
                        status = "被驳回";
                    }
                    else
                    {
                        status = "未发布";
                    }
                }
                var cateName = "草稿";
                if (sub.project_item_id.HasValue)
                {

                    var projectItem = DataFactory.Instance().ProjectItem(sub.project_item_id.Value);


                    var project = DataFactory.Instance().Project(sub.project_id.Value);

                    cateName = String.Format("{0}/{1}", project.Caption, projectItem.Caption);




                }
                var ness = sestion
                  .NewSection().AddCell("发布状态", status);

                sestion
                  .NewSection().AddCell("可读情况", (sub.Visible ?? 0) == 0 ? "关注可读" : "全网可读", new UIClick(request, "Id", sub.Id.ToString(), gKey, "Visible"));

                ness.AddCell("所属专栏", cateName
                       , new UIClick(request, "Id", sub.Id.ToString(), gKey, "Project"));

                ness.AddCell("评论功能", (sub.IsComment ?? true) ? "开启" : "关闭", new UIClick(request, "Id", Id.ToString(), gKey, "Comment"))
                  .NewSection()
                  .AddCell("浏览正文", "", new UIClick(request.Model, "View", sub.Id.ToString()))
                  .AddCell("管理评论", "", new UIClick(request.Model, "Comments", Id.ToString()));




                sestion.UIFootBar = new UIFootBar().AddText(
                new UIEventText(sub.Status == 1 ? "下架" : "确认发布").Click(new UIClick(request, "Id", Id.ToString(), "Model", "Status", "Status", sub.Status == 1 ? "-1" : "1")
                {
                    Model = request.Model,
                    Command = request.Command
                }).Style(new UIStyle().BgColor()), new UIEventText("摘正文摘要").Click(new UIClick(request, "Id", Id.ToString(), "Model", "AutoDesc")
                {
                    Model = request.Model,
                    Command = request.Command
                }));
                sestion.UIFootBar.IsFixed = true;
                sestion.SendTo("Subject.Del", this.Context, "System.Image", "Subject.Save", "Subject.Image", "Subject.Content");

            });

            var imageIndes = Utility.BitIndex(sub.ImageIndexs ?? 0);
            switch (Model)
            {
                case "Picture":
                    var seq = Utility.IntParse(this.AsyncDialog("Seq", "1"), 0);
                    this.AsyncDialog("Picture", g =>
                    {
                        var sel = new Web.UISheetDialog();
                        sel.Put(new UIClick(new UMC.Web.WebMeta().Put("id", imageKey).Put("index", seq))
                        {
                            Command = "Image",
                            Text = "重新上传",
                            Model = "System"
                        });
                        sel.Put(new UIClick(new WebMeta(request.Arguments).Put(g, "YES"))
                        {
                            Command = request.Command,
                            Text = "删除图片",
                            Model = request.Model
                        });
                        return sel;
                    });
                    if (Utility.BitIndex(sub.ImageIndexs.Value, seq))
                    {

                        DataFactory.Instance().Put(new Subject { Id = sub.Id.Value, ImageIndexs = Utility.BitIndex(sub.ImageIndexs.Value, seq, false) });

                    }
                    break;
                case "DingTalk":
                    {
                        if (sub.Status == 1)
                        {
                            switch (this.AsyncDialog("Type", g =>
                             {
                                 var ds = new UISelectDialog();
                                 ds.Options.Put("用机器人发送", "Robot");
                                 ds.Options.Put("选择到人发送", "Session");
                                 return ds;
                             }))
                            {
                                case "Robot":
                                    break;
                            }

                        }
                        var DingTalk = Web.UIDialog.AsyncDialog(this.Context, "TalkId", g =>
                         {
                             if (request.UserAgent.Contains("DingTalk"u8) == false)
                             {
                                 this.Prompt("非钉钉环境，不能获取到钉钉会话参数");
                             }
                             return this.DialogValue("none");

                         });
                        if (sub.Status == 1)
                        {
                            this.Send(request, sub, DingTalk, false);
                            this.Prompt("会话发送已经发起");
                        }
                        else
                        {
                            this.Context.Token.Put("DingTalk-Sub-Id", sub.Id.Value.ToString()).Put("DingTalk-Session-Text", this.AsyncDialog("TalkId-Text", "Text")).Put("DingTalk-Session-Id", DingTalk).Commit(request.UserHostAddress, this.Context.Server);
                        }



                    }
                    break;
                case "Image":
                    var seqValue = this.AsyncDialog("Seq", g =>
                        {
                            var ls = Utility.BitIndex(sub.ImageIndexs ?? 0);
                            var seq = 0;
                            if (ls.Length == 0)
                            {
                                seq = 1;
                            }
                            else
                            {
                                seq = ls[ls.Length - 1] + 1;
                            }
                            var dl = new Web.UISheetDialog() { Title = "图片上传" };
                            dl.Put(new Web.UIClick(sub.Id.ToString()) { Model = request.Model, Command = "Image", Text = "正文图片" });
                            dl.Put("本地图片", seq.ToString());

                            return dl;
                        });
                    this.AsyncDialog("Picture", "System", "Image", new WebMeta().Put("id", sub.Id).Put("index", seqValue));

                    DataFactory.Instance().Put(new Subject { Id = sub.Id.Value, ImageIndexs = Utility.BitIndex(sub.ImageIndexs ?? 0, Utility.IntParse(seqValue, 1), true) });


                    break;
                case "Title":
                    var title = Web.UIDialog.AsyncDialog(this.Context, "Title", g =>
                    {
                        var dl = new Web.UIFormDialog() { Title = "图文标题" };
                        dl.AddTextarea("图文标题", "Title", sub.Title);
                        dl.Submit("确认更改", "Subject.Save");
                        return dl;
                    });
                    DataFactory.Instance().Put(new Subject
                    {
                        Id = sub.Id.Value,
                        Title = title
                    });

                    break;
                case "Desc":
                    var desc = this.AsyncDialog("Desc", g =>
                     {
                         var dl = new Web.UIFormDialog() { Title = "图文摘要" };
                         dl.AddText("搜索关健字", "Keywords", sub.Keywords).PlaceHolder("搜索引擎SEO优化").NotRequired();
                         dl.AddTextarea("图文摘要", "Description", sub.Description ?? sub.Title).Put("Rows", 10);
                         dl.Submit("确认更改", "Subject.Save");
                         return dl;
                     });

                    DataFactory.Instance().Put(new Subject
                    {
                        Id = sub.Id.Value,
                        Description = desc["Description"],
                        Keywords = desc["Keywords"]
                    });
                    break;
                case "Score":
                    var Score = Utility.IntParse(Web.UIDialog.AsyncDialog(this.Context, "Score", g =>
                   {
                       var dl = new Web.UIFormDialog() { Title = "图文积分" };
                       dl.AddNumber("图文积分", "Score", sub.Score);
                       dl.Submit("确认更改", "Subject.Save");
                       return dl;
                   }), 0);
                    if (Score < 0)
                    {
                        this.Prompt("积分必须大于或等于零");
                    }
                    DataFactory.Instance().Put(new Subject
                    {
                        Id = sub.Id.Value,
                        Score = Score
                    });
                    break;
                case "Project":
                    {
                        if (sub.project_id.HasValue)
                        {
                            var member = DataFactory.Instance().ProjectMember(sub.project_id.Value, user.Id.Value);
                            if (member != null)
                            {
                                switch (member.AuthType)
                                {
                                    case WebAuthType.Admin:
                                    case WebAuthType.User:
                                        break;
                                    default:
                                        this.Prompt("您未有编辑此图文的权限");
                                        break;
                                }

                            }
                            else
                            {
                                this.Prompt("您未有编辑此图文的权限");
                            }
                        }
                        var meta = new WebMeta();
                        meta.Put("Project", sub.project_id);

                        var sid = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("PortfolioId", request.Model, "Portfolio", meta)).Value;

                        var portfolio = DataFactory.Instance().Portfolio(sid);

                        var projectItem = DataFactory.Instance().ProjectItem(portfolio.project_item_id.Value);

                        var project = DataFactory.Instance().Project(portfolio.project_id.Value);


                        var mb = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);
                        if (mb == null)
                        {
                            this.Prompt("你尚未加入此项目的专栏");
                        }
                        else
                        {
                            switch (mb.AuthType)
                            {
                                case WebAuthType.Admin:
                                case WebAuthType.User:
                                    break;
                                default:
                                    this.Prompt("你无此专栏的编辑权限");
                                    break;
                            }
                        }

                        DataFactory.Instance().Put(new Subject
                        {
                            Id = sub.Id.Value,
                            portfolio_id = portfolio.Id,
                            project_id = projectItem.project_id,
                            project_item_id = projectItem.Id,
                            last_user_id = user.Id
                        });
                        //}
                    }
                    break;
                case "Comment":
                    var s2 = UMC.Data.Utility.IntParse(this.AsyncDialog("Comment", g =>
                    {
                        return new Web.UISheetDialog() { Title = "评论功能" }.Put("开启评论", "1").Put("关闭评论", "-1");

                    }), 0);
                    DataFactory.Instance().Put(new Subject
                    {
                        Id = sub.Id.Value,
                        IsComment = s2 == 1
                    });
                    break;
                case "Status":
                    var s = UMC.Data.Utility.IntParse(this.AsyncDialog("Status", g =>
                   {
                       var dl = new Web.UISelectDialog() { Title = "发布确认" };
                       dl.Options.Add("不发布", "-1");
                       dl.Options.Add("发布", "1");
                       return dl;
                   }), 0);
                    if (sub.project_id.HasValue == false || (sub.project_item_id ?? 0) == 0 || (sub.portfolio_id ?? 0) == 0)
                    {
                        this.Prompt("请选择发布的栏位");
                    }

                    if (s == 0)
                    {
                        if (String.IsNullOrEmpty(sub.Url) == false && sub.Status == -1)
                        {
                            s = 1;
                        }
                    }
                    if (s == -1 && sub.Status == -2)
                    {
                        this.Prompt("被驳回状态，不需要此操作");
                    }

                    String Sdesc = null;
                    if (s > 0)
                    {

                        if (String.IsNullOrEmpty(sub.Description))
                        {
                            var content = DataFactory.Instance().Content(sub.Id.Value) ?? new SubjectContent();

                            var celss = UMC.Data.JSON.Deserializes<WebMeta>((String.IsNullOrEmpty(content.DataJSON) ? "[]" : content.DataJSON)) ?? new UMC.Web.WebMeta[] { };
                            var sb = new StringBuilder();
                            foreach (var pom in celss)
                            {
                                switch (pom["type"])
                                {
                                    case "CMSText":
                                        var value = pom.GetMeta("value");
                                        var format = pom.GetMeta("format")["text"];
                                        var fValue = Utility.Format(format, value.GetDictionary(), String.Empty);
                                        if (String.Equals(fValue, sub.Title) == false)
                                        {
                                            sb.Append(fValue);
                                        }
                                        if (sb.Length > 250)
                                        {
                                            break;
                                        }

                                        break;
                                }
                            }
                            Sdesc = sb.Length > 250 ? sb.ToString(0, 250) : sb.ToString();
                            sub.Description = Sdesc;
                        }


                        DataFactory.Instance().Put(new Subject
                        {
                            Id = sub.Id.Value,
                            Status = s,
                            Description = Sdesc,
                            Poster = user.Alias,
                            PublishTime = Utility.TimeSpan() - 100000,
                            ReleaseTime = DateTime.Now
                        });

                        this.Prompt("发布成功", false);
                    }
                    else
                    {

                        DataFactory.Instance().Put(new Subject
                        {
                            Id = sub.Id.Value,
                            Status = s,
                        });

                    }
                    this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.Portfolio.Item").Put("id", sub.Id.Value).Put("hide", s != 1), false);

                    break;
                case "AutoDesc":
                    {

                        var content = DataFactory.Instance().Content(sub.Id.Value) ?? new SubjectContent();
                        var celss = UMC.Data.JSON.Deserializes<WebMeta>((String.IsNullOrEmpty(content.DataJSON) ? "[]" : content.DataJSON)) ?? new UMC.Web.WebMeta[] { };
                        var sb = new StringBuilder();
                        foreach (var pom in celss)
                        {
                            switch (pom["type"])
                            {
                                case "CMSText":
                                    var value = pom.GetMeta("value");
                                    var format = pom.GetMeta("format")["text"];

                                    var fValue = Utility.Format(format, value.GetDictionary(), String.Empty);
                                    if (String.Equals(fValue, sub.Title) == false)
                                    {
                                        sb.Append(fValue);
                                    }
                                    if (sb.Length > 250)
                                    {
                                        break;
                                    }

                                    break;
                            }
                        }
                        var Sdesc2 = sb.Length > 250 ? sb.ToString(0, 250) : sb.ToString();


                        DataFactory.Instance().Put(new Subject
                        {
                            Id = sub.Id.Value,
                            Description = Sdesc2
                        });

                    }
                    break;
                case "Show":
                    var m = this.AsyncDialog("Show", g =>
                    {
                        var dl = new Web.UISelectDialog() { Title = "封面展示方式" };
                        dl.Options.Put("封面大图形式", "Max").Put("封面小图形式", "Min");
                        return dl;
                    });
                    DataFactory.Instance().Put(new Subject
                    {
                        Id = sub.Id.Value,
                        IsPicture = String.Equals(m, "Max")
                    });
                    break;
                case "Visible":
                    var Visible = this.AsyncDialog("Visible", g =>
                    {
                        var dl = new Web.UISelectDialog() { Title = "可读情况" };
                        dl.Options.Put("全网可读", "1").Put("关注可读", "0");
                        return dl;
                    });
                    switch (Visible)
                    {
                        case "true":
                            DataFactory.Instance().Put(new Subject
                            {
                                Id = sub.Id.Value,
                                Visible = 1
                            });
                            response.Redirect(new WebMeta().Put("visible", true).Put("id", sub.Id));
                            break;
                        case "false":
                            DataFactory.Instance().Put(new Subject
                            {
                                Id = sub.Id.Value,
                                Visible = 0
                            });
                            response.Redirect(new WebMeta().Put("visible", false).Put("id", sub.Id));
                            break;
                    }

                    DataFactory.Instance().Put(new Subject
                    {
                        Id = sub.Id.Value,
                        Visible = Utility.IntParse(Visible, 0)
                    });
                    break;
                case "Del":
                    {
                        DataFactory.Instance().Put(new Subject
                        {
                            Id = sub.Id.Value,
                            Status = -2,
                            last_user_id = user.Id.Value,
                            portfolio_id = 0,
                            project_item_id = 0,
                            LastDate = DateTime.Now,
                            ReleaseTime = DateTime.Now,
                        });
                        var projectItem = DataFactory.Instance().ProjectItem(sub.project_item_id.Value);
                        DataFactory.Instance().Put(new ProjectItem
                        {
                            Id = projectItem.Id,
                            SubjectTotal = (projectItem.SubjectTotal ?? 0) - 1
                        });
                        var portfolio = DataFactory.Instance().Portfolio(sub.portfolio_id.Value);
                        DataFactory.Instance().Put(new Portfolio
                        {
                            Id = portfolio.Id,
                            SubjectTotal = (portfolio.SubjectTotal ?? 0) - 1
                        });


                    }
                    this.Context.Send("Subject.Del", new WebMeta().Put("Id", sub.Id), false);
                    break;
            }

            this.Context.Send("Subject.Save", true);
        }
    }
}